#include <iostream>
#include <memory>

#include "TcpServer.hpp"
#include "LogMessage.hpp"
#include "InetAddr.hpp"
#include "Calculator.hpp"
#include "Protocol.hpp"

void Usage()
{
    std::cout << "./Server port" << std::endl;
}

//
bool Headler(std::string& instreambuffer, std::string* out)
{
    //计算器
    Calculator::Calculator cal;

    //构建相应对象
    Protocol::Factory fact;
    auto request = fact.BulidRequest();

    std::string message;
    std::string temp;
    while (Protocol::DeCode(instreambuffer, &message) != false)
    {
        //读到了一个完整的报文，可以开始处理了
        if (request->Deserialization(message) == false)
            return false;

        std::cout << "Request: " << message << std::endl;
        auto respose = cal.Compute(request);
        respose->Serialization(&temp);
        std::cout << "Response: " << temp << std::endl;

        Protocol::EnCode(temp);
        *out += temp;
    }

    return true;
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage();
        exit(4);
    }

    uint16_t port = atoi(argv[1]);
    TcpServer* http = new TcpServer(port, Headler);
    http->Start();

    delete http;

    return 0;
}